import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {

    private JTextField display;
    private String currentNumber;
    private String lastOperator;
    private double result;

    public Calculator() {
        setTitle("计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 400);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建显示文本域
        display = new JTextField();
        display.setHorizontalAlignment(JTextField.RIGHT);
        panel.add(display, BorderLayout.NORTH);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

        String[] buttons = {"7", "8", "9", "/",
                "4", "5", "6", "*",
                "1", "2", "3", "-",
                "0", ".", "=", "+"};

        for (String button : buttons) {
            JButton btn = new JButton(button);
            btn.addActionListener(this);
            buttonPanel.add(btn);
        }

        panel.add(buttonPanel, BorderLayout.CENTER);

        add(panel);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

        if (command.matches("[0-9]") || command.equals(".")) {
            currentNumber = display.getText() + command;
            display.setText(currentNumber);
        } else if (command.equals("/") || command.equals("*") ||
                command.equals("-") || command.equals("+")) {
            lastOperator = command;
            result = Double.parseDouble(display.getText());
            display.setText("");
        } else if (command.equals("=")) {
            if (lastOperator != null) {
                double secondOperand = Double.parseDouble(display.getText());
                switch (lastOperator) {
                    case "/":
                        result /= secondOperand;
                        break;
                    case "*":
                        result *= secondOperand;
                        break;
                    case "-":
                        result -= secondOperand;
                        break;
                    case "+":
                        result += secondOperand;
                        break;
                }
                display.setText(String.valueOf(result));
                lastOperator = null;
            }
        }
    }

    public static void main(String[] args) {
        new Calculator();
    }
}
